/* globals jQuery:false, system:false  */

(function($) {
  $(
    (function(win) {
      const AJAX_REGION_URL = system.api_domain + '/get_option?category=region'

      const regionPicker = {
        pickerCollection: [],

        init() {
          console.log('init')
          if (this.__checkPickerExist()) {
            this.makePickerCollection()
              .getInitialRegion()
              .__bindEvent()
              .__checkIfDefaultProvince()
          }
          else {
          }
        },

        __checkIfDefaultProvince() {
          this.pickerCollection.forEach(picker => {
            if (picker.province && picker.province.data('defaults')) {
              $(picker.province).trigger('change', [
                picker.province.data('defaults'),
              ])
            }
            if (picker.city && picker.city.data('defaults')) {
              $(picker.city).trigger('change', [
                picker.city.data('defaults'),
              ])
            }
          })
          return this
        },

        getInitialRegion() {
          this.__getRegion().province()
          return this
        },

        __makeOptions(optionsData, defaultValue) {
          let options = ''

          const makeNormalOption = function(optionData) {
            const option = [
              '<option value=\'' + optionData.id + '\'>',
              optionData.name,
              '</option>',
            ].join('')

            return option
          }

          const makeSelectedOption = function(optionData) {
            const option = [
              '<option value=\'' + optionData.id + '\' selected>',
              optionData.name,
              '</option>',
            ].join('')

            return option
          }

          $.each(optionsData, (idx, optionData) => {
            if (defaultValue && defaultValue === Number(optionData.id)) {
              options += makeSelectedOption(optionData)
            }
            else {
              options += makeNormalOption(optionData)
            }
          })

          return options
        },

        __getRegion() {
          const _this = this

          const coreAjax = function(param, successCB) {
            $.ajax({
              url: AJAX_REGION_URL,
              data: {pid: param},
              dataType: 'jsonp',
              type: 'GET',
              success(dataset) {
                if (dataset.status === 'success') successCB(dataset.data)
              },
            })
          }

          const coreProcess = function(dataset, regionName) {
            _this.pickerCollection.forEach(picker => {
              let options = ``

              if (picker[regionName] && picker[regionName].data('defaults')) {
                options += `<option value="" >请选择</option>`
options += _this.__makeOptions(dataset, picker[regionName].data('defaults')
)
}
else {
    options += `<option value="" selected>请选择</option>`
    options += _this.__makeOptions(dataset)
}

$(picker[regionName]).html(options)
})
}

return {
    province(successCB) {
        return coreAjax(0, dataset => {
            coreProcess(dataset, 'province')
        })
    },
    city(brandId, successCB) {
        return coreAjax(brandId, dataset => {
            coreProcess(dataset, 'city')
        })
    },
    area(id, successCB) {
        return coreAjax(id, dataset => {
            coreProcess(dataset, 'area')
        })
    }
}
},

__bindEvent() {
    this.__bindProvinceEvent()
    this.__bindCityEvent()
    return this
},

__bindProvinceEvent() {
    /**
     *
     * 为所有第一次省级下拉绑定 change 事件。
     * 传入父级 blcok 作为 ref，for late use。
     *
     */
    this.pickerCollection.forEach(picker => {
        $(picker.block).on(
            'change',
            'select.province_id',
            {picker},
            this.provinceDidChange.bind(this)
        )
    })
},

__bindCityEvent() {
    /**
     *
     * 为所有第一次省级下拉绑定 change 事件。
     * 传入父级 blcok 作为 ref，for late use。
     *
     */
    this.pickerCollection.forEach(picker => {
        $(picker.block).on(
            'change',
            'select.city_id',
            {picker},
            this.cityDidChange.bind(this)
        )
    })
},

provinceDidChange(e, defaultValue) {
    e.preventDefault()
    e.stopPropagation()

    const $picker = e.data.picker
    const $target = $(e.currentTarget)
    const $value = defaultValue || $target.val()

    const $city = $picker.city
    const _this = this

    $.ajax({
        url: AJAX_REGION_URL,
        data: {pid: $value},
        dataType: 'jsonp',
        type: 'GET',
        success(dataset) {
            if (dataset.status === 'success') {
                let options = `<option value="">请选择</option>`
                options += _this.__makeOptions(dataset.data, $city.data('defaults'))
                $city.html(options)
            }
        },
    })

    // $city.on('change', e => {
    //   e.preventDefault()
    //
    //   $.ajax({
    //     url: AJAX_REGION_URL,
    //     data: {pid: $value},
    //     dataType: 'jsonp',
    //     type: 'GET',
    //     success(dataset) {
    //       if (dataset.status === 'success') {
    //         console.log(dataset)
    //       }
    //     },
    //   })
    // })
    // this.__getRegion().city($value)
},

cityDidChange(e, defaultValue) {
    e.preventDefault()
    e.stopPropagation()

    const $picker = e.data.picker
    const $target = $(e.currentTarget)
    const $value = defaultValue || $target.val()

    const $area = $picker.area
    const _this = this

    $.ajax({
        url: AJAX_REGION_URL,
        data: {pid: $value},
        dataType: 'jsonp',
        type: 'GET',
        success(dataset) {
            if (dataset.status === 'success') {
                let options = `<option value="">请选择</option>`
                options += _this.__makeOptions(dataset.data, $area.data('defaults'))
                $area.html(options)
            }
        },
    })
},

__checkPickerExist() {
    return $('select.province_id').length > 0
},

makePickerCollection() {
    $('select.province_id').each((_, province) => {
        const pair = {
            province: $(province),
            block: $(province).parents('.form-picker'),
            city: $(province)
                .parents('.form-picker')
                .find('select.city_id'),
            area: $(province)
                .parents('.form-picker')
                .find('select.area_id'),
        }
        this.pickerCollection.push(pair)
    })

    return this
},
}

/**
 * CarPicker Class
 * @pickerBlock class 为 form-picker 的容器
 *
 */

/**
 * 初始项目
 */
$(document).ready(() => {
    /* 初始化二级、三级地区选择联动 */
    regionPicker.init()
})
})(window)
)
})(jQuery)
;(function($) {
    $.getScript = function(src, func) {
        const script = document.createElement('script')
        script.async = 'async'
        script.src = src
        if (func) {
            script.onload = func
        }
        document.getElementsByTagName('head')[0].appendChild(script)
    }
})(jQuery)
